/**
 * @扁平路由转化成树形
 * @亮点是可以自动配置路由
 */

//require.context("路径","是否递归引入","正则")一次导入多个模块

let paths = require.context("@/pages/home", true, /\.vue$/);
//拿到所有路径 拼接到pages
// console.log(paths.keys());

//创建路由配置
let repeatRoutes = paths.keys().map((path) => {
  //通过正则去掉index.vue 或者去掉.vue得后缀
  let regExp = /(\/index\.vue|\.vue)$/;
  path = path.substring(1).replace(regExp, "");
  // console.log(path)
  return {
    path: path ? path : "/home",
    component: () => import("@/pages/home" + path),
  };
});

//处理扁平化

function convertTree(repeatRoutes) {
  //装扁平化好得数据
  let treeRoutes = [];
  //添加id 和 pid
  repeatRoutes.forEach((route) => {
    //去掉路径第一个斜杠  转换成一个数组
    let routePathArr = route.path.substring(1).split("/");
    // console.log(routePathArr);
    //length1为二级路由  length2为三级路由
    //添加自己得id
    route.id = routePathArr.join("-")
    if (routePathArr.length > 1) {
      //浅拷贝routePatheArr
      let pathArr = [...routePathArr];
      pathArr.pop();
      let pid = pathArr.join("-");
      route.pid = pid
    //   console.log(route);//添加父节点
    }
  });
  //转换成树形数据
  //找父节点
  repeatRoutes.forEach(route =>{
      let parent = repeatRoutes.find(v => route.pid === v.id);
      if(parent){
         if(!parent.children){
            parent.children = []
         }
         route.path = route.path.substring(1).split("/").pop();
         //console.log(route.path)
         parent.children.push(route)
      }else{
        treeRoutes.push(route)
      }
  });
  return treeRoutes;
}
let res = convertTree(repeatRoutes);
console.log(res);



//单独整个浅拷贝
export default [...res];